import React, {useState, useEffect} from 'react';
import { Select, Tag, message } from 'antd';
import { TagListItem } from '../data';
import { getTagList } from '../service';

interface TagsProps {
  topOrgId:number;
  value:string;
  selectChange: (values:any) => void;
  form:any;
}

const { Option } = Select;

const TagCommonComponent: React.FC<TagsProps> = (props) => {

  const { topOrgId, value, form, selectChange } = props;
  
  const [list, setList] = useState([]);
  const getList = (topOrgId:number) =>{
    const param = new Object();
    param["orgId"] = topOrgId;
    new Promise((resolve, reject) => {
      getTagList(param)
        .then((res) => {
          if (res && res.code === 200) {
            setList(res.data);
            resolve(true);
          } else {
            message.error('请求失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }

  useEffect(() => {
    if(form){
      form?.setFieldsValue({"tagIds":null});
    }
    
  },[topOrgId]);

  const tagRender = (props:any) => {
    const { label, closable, onClose } = props;
    return (
      <Tag color="blue" closable={closable} onClose={onClose} title={label} style={{ marginRight: 3,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:170 }}>
        {label}
      </Tag>
    );
  }
  return (
      <Select
        mode="tags"
        showArrow
        tagRender={tagRender}
        placeholder="请选择标签"
        optionFilterProp="children"
        value={value&&value!=""?value.split(",").map(Number):undefined}
        allowClear
        style={{ width: 200 }}
        onChange={(values) =>selectChange(values)}
        onFocus={() => getList(topOrgId)}
        tokenSeparators={[',']}
      >
        {list.map((item:TagListItem) => <Option key={item.id} value={item.id}>{item.name}</Option>)}
    </Select>
  );
};

export default TagCommonComponent;
